<template>
  <div class="chat-container">
    <!-- 辩论设置区域 -->
    <div class="debate-settings" v-if="!debateStarted">
      <div class="settings-card">
        <h3 class="settings-title">辩论设置</h3>
        <div class="settings-form">
          <div class="form-item">
            <label class="form-label">辩论题目：</label>
            <el-input 
              v-model="debateTopic" 
              placeholder="请输入辩论题目，例如：人工智能是否应该被广泛使用"
              type="textarea"
              :rows="3"
              maxlength="200"
              show-word-limit
            />
          </div>
          <div class="form-item">
            <label class="form-label">选择立场：</label>
            <el-select v-model="userSide" placeholder="请选择您的立场" style="width: 100%">
              <el-option label="正方" value="正方" />
              <el-option label="反方" value="反方" />
            </el-select>
          </div>
          <div class="form-item">
            <el-button 
              type="primary" 
              @click="startDebate"
              :disabled="!debateTopic || !userSide"
              style="width: 100%"
            >
              开始辩论
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天记录区域 -->
    <div class="messages-container" ref="messagesContainer" v-if="debateStarted">
      <!-- 辩论信息显示 -->
      <div class="debate-info">
        <div class="debate-header">
          <h3>辩论题目：{{ debateTopic }}</h3>
          <div class="debate-sides">
            <span class="side-tag user-side">您：{{ userSide }}</span>
            <span class="side-tag ai-side">AI：{{ aiSide }}</span>
          </div>
        </div>
      </div>
      
      <!-- 欢迎消息 -->
      <div class="message message-bot">
        <div class="message-content welcome-message">
          辩论开始！我是{{ aiSide }}，请开始您的辩论发言。
          <div class="message-actions">
            <button class="action-btn" @click="copyMessage('辩论开始！我是' + aiSide + '，请开始您的辩论发言。')">
              <i class="fas fa-copy"></i>
            </button>
          </div>
        </div>
      </div>
      
      <div v-for="(message, index) in messages" 
           :key="index" 
           :class="['message', message.type === 'user' ? 'message-user' : 'message-bot']">
        <div class="message-content">
          <div v-if="message.type === 'bot'" class="bot-message">
            <div v-html="renderMarkdown(message.text)"></div>
            <div class="message-actions bot-actions">
              <el-button class="copy-button" size="small" @click="copyMessage(message.text)">
                <el-icon><Document /></el-icon>
                复制
              </el-button>
              <button v-if="index === messages.length - 1 && message.type === 'bot'" 
                      class="action-btn" 
                      @click="regenerateResponse"
                      :disabled="loading">
                <i class="fas fa-redo"></i>
              </button>
            </div>
          </div>
          <div v-else class="user-message">
            <div class="user-input-text">{{ message.text }}</div>
            <div class="message-actions">
              <el-button class="copy-button" size="small" @click="copyMessage(message.text)">
                <el-icon><Document /></el-icon>
                复制
              </el-button>
              <el-button 
                class="regenerate-button" 
                size="small" 
                @click="regenerateUserMessage(message)"
                :disabled="loading"
              >
                <el-icon><RefreshRight /></el-icon>
                重新生成
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 输入组件 -->
    <Input 
      v-if="debateStarted"
      @send="handleSend" 
      :disabled="loading"
      placeholder="请输入您的辩论观点..."
    />

    <!-- 重新开始辩论按钮 -->
    <div class="restart-debate" v-if="debateStarted">
      <el-button @click="restartDebate" type="info" size="small">
        <el-icon><RefreshRight /></el-icon>
        重新开始辩论
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, computed } from 'vue'
import Input from '@/components/Input.vue'
import requestUtil from '@/util/request'
import { Document, RefreshRight, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'

// 配置marked选项
marked.setOptions({
  breaks: true, // 支持GitHub风格的换行
  gfm: true,    // 启用GitHub风格的Markdown
  headerIds: false, // 禁用标题ID
  mangle: false,    // 禁用标题ID混淆
  sanitize: false   // 允许HTML标签
})

const messages = ref([])
const loading = ref(false)
const messagesContainer = ref(null)

// 辩论相关状态
const debateStarted = ref(false)
const debateTopic = ref('')
const userSide = ref('')
const sessionId = ref('')

// 计算AI的立场
const aiSide = computed(() => {
  return userSide.value === '正方' ? '反方' : '正方'
})

// 获取当前登录用户信息
const currentUser = ref({
  username: '用户', // 默认值，实际应该从登录状态获取
  nickname: '用户'
})

// 获取用户信息
const getUserInfo = () => {
  // 这里应该从localStorage或vuex获取当前登录用户信息
  // 暂时使用默认值，实际项目中需要根据登录状态获取
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo)
      currentUser.value = {
        username: user.username || '用户',
        nickname: user.nickname || user.username || '用户'
      }
    } catch (e) {
      console.error('解析用户信息失败:', e)
    }
  }
}

// 开始辩论
const startDebate = () => {
  if (!debateTopic.value || !userSide.value) {
    ElMessage.warning('请填写辩论题目并选择立场')
    return
  }
  
  debateStarted.value = true
  sessionId.value = `debate_${Date.now()}`
  
  // 清空之前的消息
  messages.value = []
  
  ElMessage.success('辩论已开始！')
}

// 重新开始辩论
const restartDebate = () => {
  debateStarted.value = false
  debateTopic.value = ''
  userSide.value = ''
  messages.value = []
  sessionId.value = ''
}

// 渲染Markdown
const renderMarkdown = (text) => {
  return marked(text)
}

// 复制消息内容
const copyMessage = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage({
      message: '复制成功',
      type: 'success',
      duration: 2000
    })
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage({
      message: '复制失败',
      type: 'error',
      duration: 2000
    })
  }
}

// 重新生成回复
const regenerateResponse = async () => {
  if (loading.value || messages.value.length < 2) return
  
  // 获取最后一条用户消息
  const lastUserMessage = [...messages.value].reverse().find(m => m.type === 'user')
  if (!lastUserMessage) return

  // 移除最后一条机器人消息
  messages.value.pop()
  
  // 重新发送请求
  loading.value = true
  try {
    const response = await requestUtil.post('/user/student/', {
      topic: debateTopic.value,
      user_side: userSide.value,
      message: lastUserMessage.text,
      session_id: sessionId.value
    })
    
    messages.value.push({
      type: 'bot',
      text: response.data.message || '抱歉，我现在无法回答您的问题。'
    })

    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('Error:', error)
    messages.value.push({
      type: 'bot',
      text: '抱歉，发生了一些错误，请稍后再试。'
    })
  } finally {
    loading.value = false
  }
}

// 重新生成用户消息的回复
const regenerateUserMessage = async (message) => {
  if (loading.value) return
  
  // 设置加载状态
  loading.value = true

  try {
    // 添加用户消息（复制之前的消息）
    messages.value.push({
      type: 'user',
      text: message.text
    })

    // 重新发送请求
    const response = await requestUtil.post('/user/student/', {
      topic: debateTopic.value,
      user_side: userSide.value,
      message: message.text,
      session_id: sessionId.value
    })
    
    // 添加新的机器人回复
    messages.value.push({
      type: 'bot',
      text: response.data.message || '抱歉，我现在无法回答您的问题。'
    })

    // 滚动到底部
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('Error:', error)
    messages.value.push({
      type: 'bot',
      text: '抱歉，发生了一些错误，请稍后再试。'
    })
  } finally {
    loading.value = false
  }
}

// 处理消息发送
const handleSend = async (message) => {
  // 添加用户消息
  messages.value.push({
    type: 'user',
    text: message.text
  })

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 设置加载状态
  loading.value = true

  // 显示等待提示
  const loadingMessage = ElMessage({
    message: 'AI正在思考回复，请耐心等待...',
    type: 'info',
    duration: 0, // 持续显示，直到手动关闭
    showClose: true
  })

  try {
    // 创建一个超时Promise
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时')), 60000) // 60秒超时
    })

    // 创建实际的请求Promise
    const requestPromise = requestUtil.post('/user/student/', {
      topic: debateTopic.value,
      user_side: userSide.value,
      message: message.text,
      session_id: sessionId.value
    })

    // 使用Promise.race来竞争
    const response = await Promise.race([requestPromise, timeoutPromise])
    
    // 检查响应数据
    if (!response.data || !response.data.message) {
      throw new Error('响应数据格式错误')
    }

    // 添加机器人回复
    messages.value.push({
      type: 'bot',
      text: response.data.message
    })

    // 滚动到底部
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('Error:', error)
    
    // 根据错误类型显示不同的错误消息
    let errorMessage = '抱歉，发生了一些错误，请稍后再试。'
    
    if (error.message === '请求超时') {
      errorMessage = 'AI思考时间过长，请稍后重试...'
    } else if (error.response) {
      // 处理HTTP错误
      switch (error.response.status) {
        case 500:
          errorMessage = '服务器内部错误，请稍后重试'
          break
        case 404:
          errorMessage = '请求的资源不存在'
          break
        default:
          errorMessage = `请求失败 (${error.response.status})`
      }
    } else if (error.message === '响应数据格式错误') {
      errorMessage = '服务器返回的数据格式不正确'
    }
    
    messages.value.push({
      type: 'bot',
      text: errorMessage
    })
  } finally {
    // 关闭加载提示
    loadingMessage.close()
    loading.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 组件挂载时获取用户信息
getUserInfo()
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
  padding: 15px;
  background-color: #f5f7fa;
}

.debate-settings {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.settings-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 500px;
}

.settings-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.settings-form {
  .form-item {
    margin-bottom: 20px;
    
    .form-label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: #333;
    }
  }
}

.debate-info {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.debate-header {
  h3 {
    margin: 0 0 15px 0;
    font-size: 18px;
    font-weight: 600;
  }
}

.debate-sides {
  display: flex;
  gap: 15px;
  
  .side-tag {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    
    &.user-side {
      background-color: rgba(255, 255, 255, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.3);
    }
    
    &.ai-side {
      background-color: rgba(255, 255, 255, 0.15);
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
  }
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  margin-bottom: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  /* 优化滚动条样式 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #A3BE8C;
    border-radius: 3px;
    transition: background-color 0.3s ease;
    
    &:hover {
      background-color: darken(#A3BE8C, 10%);
    }
  }

  &::-webkit-scrollbar-track {
    background-color: #f5f7fa;
  }
}

.message {
  margin-bottom: 15px;
  display: flex;
  animation: fadeIn 0.5s ease-out;
  
  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  &:last-child {
    margin-bottom: 0;
  }
}

.message-bot {
  justify-content: flex-start;
  
  .message-content {
    position: relative;
    background-color: #A3BE8C;
    border-radius: 10px;
    padding: 10px 14px;
    max-width: 75%;
    color: white;
    margin-left: 10px;

    &::before {
      content: '';
      position: absolute;
      left: -6px;
      top: 50%;
      transform: translateY(-50%);
      width: 0;
      height: 0;
      border-top: 6px solid transparent;
      border-bottom: 6px solid transparent;
      border-right: 6px solid #A3BE8C;
    }
  }
}

.message-user {
  justify-content: flex-end;
  
  .message-content {
    position: relative;
    background-color: #e4e4e6;
    border-radius: 10px;
    padding: 10px 14px;
    max-width: 75%;
    color: #333;
    margin-right: 10px;

    &::after {
      content: '';
      position: absolute;
      right: -6px;
      top: 50%;
      transform: translateY(-50%);
      width: 0;
      height: 0;
      border-top: 6px solid transparent;
      border-bottom: 6px solid transparent;
      border-left: 6px solid #e4e4e6;
    }
  }
}

.welcome-message {
  font-size: 15px;
  font-weight: 500;
  line-height: 1.6;
  letter-spacing: 0.3px;
  opacity: 0.95;
  max-width: 55% !important;
  
  animation: fadeIn 0.5s ease-out;
}

.message-actions {
  position: absolute;
  right: 0;
  bottom: -32px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.bot-actions {
  left: 0;
  right: auto;
  justify-content: flex-start;
}

.copy-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  font-size: 12px;
  color: #666;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
  
  &:hover {
    color: #409EFF;
    border-color: #409EFF;
    background-color: #ecf5ff;
  }
  
  .el-icon {
    font-size: 14px;
  }
}

.message-content {
  position: relative;
  
  &:hover {
    .message-actions {
      opacity: 1;
    }
  }
}

.action-btn {
  background: none;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
  color: #666;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
  
  &:hover {
    background-color: rgba(163, 190, 140, 0.1);
    color: #A3BE8C;
  }
  
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    
    &:hover {
      background: none;
      color: #666;
    }
  }
  
  i {
    font-size: 16px;
  }
}

.regenerate-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  font-size: 12px;
  color: #666;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
  
  &:hover:not(:disabled) {
    color: #67C23A;
    border-color: #67C23A;
    background-color: #f0f9eb;
  }
  
  &:disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }
  
  .el-icon {
    font-size: 14px;
  }
}

.restart-debate {
  text-align: center;
  margin-top: 15px;
}

// 添加Markdown样式
:deep(.bot-message) {
  h1, h2, h3, h4, h5, h6 {
    margin-top: 1em;
    margin-bottom: 0.5em;
    font-weight: 600;
    line-height: 1.25;
  }

  h1 { font-size: 1.5em; }
  h2 { font-size: 1.3em; }
  h3 { font-size: 1.2em; }
  h4 { font-size: 1.1em; }
  h5 { font-size: 1em; }
  h6 { font-size: 0.9em; }

  p {
    margin: 0.5em 0;
    line-height: 1.6;
  }

  ul, ol {
    margin: 0.5em 0;
    padding-left: 2em;
  }

  li {
    margin: 0.25em 0;
  }

  code {
    background-color: rgba(0, 0, 0, 0.1);
    padding: 0.2em 0.4em;
    border-radius: 3px;
    font-family: monospace;
  }

  pre {
    background-color: rgba(0, 0, 0, 0.1);
    padding: 1em;
    border-radius: 5px;
    overflow-x: auto;
    margin: 0.5em 0;

    code {
      background-color: transparent;
      padding: 0;
    }
  }

  blockquote {
    margin: 0.5em 0;
    padding-left: 1em;
    border-left: 4px solid rgba(0, 0, 0, 0.2);
    color: rgba(0, 0, 0, 0.6);
  }

  table {
    border-collapse: collapse;
    margin: 0.5em 0;
    width: 100%;

    th, td {
      border: 1px solid rgba(0, 0, 0, 0.2);
      padding: 0.5em;
    }

    th {
      background-color: rgba(0, 0, 0, 0.1);
    }
  }
}
</style>